package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Api("通用接口")
@RequestMapping("/admin/common")
@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名：{}", originalFilename);
        String url = null;

        try {
            //1.1构造参数，字节数组，文件名
            byte[] bytes = file.getBytes();
            //获取文件名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //通过UUID生成唯一的文件名，可以防止文件被覆盖
            String objectName = UUID.randomUUID().toString() + suffix;
            //1，调用AliOssUtils将前端传递的文件保存到阿里云
            url = aliOssUtil.upload(bytes, objectName);
        } catch (IOException e) {
            log.info("文件上传失败：{}", e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        //返回图片路径
        return Result.success(url);
    }
}
